package com.collectplus.express.tools;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.widget.Toast;

@SuppressLint("NewApi")
public class DownloadReceiver extends BroadcastReceiver {

	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		mContext = context;
		String action = intent.getAction();
		if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
			Toast.makeText(context, "下载完成...", Toast.LENGTH_LONG).show();
			long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); // TODO 判断这个id与之前的id是否相等，如果相等说明是之前的那个要下载的文件
			SharedPreferences spf = context.getSharedPreferences("download", Context.MODE_PRIVATE);
			if (id != spf.getLong("download_id", 0)) {
				return;
			}

			installApp(downloadIdToPath(mContext, id));
		} else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
			Toast.makeText(context, "下载中，请稍后...", Toast.LENGTH_LONG).show();
		}
	}

	private void installApp(String filePath) {
		File _file = new File(filePath);
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addCategory("android.intent.category.DEFAULT");
		Uri uri = Uri.fromFile(_file);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");

		mContext.startActivity(intent);
	}
	
	public String downloadIdToPath(Context context, long id) {
		Query query = new Query();
		query.setFilterById(id);
		DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		Cursor cursor = downloadManager.query(query);

		int columnCount = cursor.getColumnCount();
		while (cursor.moveToNext()) {
			for (int j = 0; j < columnCount; j++) {
				String columnName = cursor.getColumnName(j);
				String string = cursor.getString(j);
				if (columnName.equals("local_filename")) {
					return string;
				}
				if (string != null) {
					System.out.println(columnName + ": " + string);
				} else {
					System.out.println(columnName + ": null");
				}
			}
		}
		cursor.close();
		return null;
	}
}
